package com.fejal.dao;


import java.util.List;
import com.fejal.bean.Disciplina;


public class DisciplinaDAOHibernate implements DisciplinaDAO {

	HibernateDAOFactory hibernateDAOFactory = null;
	HibernateDAO<Disciplina> hibernateDAO = null;

	public DisciplinaDAOHibernate() {
		hibernateDAOFactory = new HibernateDAOFactory();
		hibernateDAO = hibernateDAOFactory.getDisciplinaDao();
	}

	@Override
	public boolean inserir(Disciplina disciplina) throws Exception {

		boolean ok = false;

		try {
			hibernateDAO.add(disciplina);
			ok = true;

		} catch (Exception e) {
			throw new Exception(e.getMessage());
		} 
		return ok;
	}

	@Override
	public boolean alterar(Disciplina disciplina) throws Exception {

		boolean ok = false;
	
		
		try {
			hibernateDAO.update(disciplina);
			ok = true;

		} catch (Exception e) {
			throw new Exception(e.getMessage());
		} 

		return ok;
	}

	@Override
	public boolean excluir(Disciplina disciplina) throws Exception {

		boolean ok = false;

		try {
			hibernateDAO.remove(disciplina);
			ok = true;

		} catch (Exception e) {
			throw new Exception(e.getMessage());
		} 

		return ok;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Disciplina> getSelecionar(String identificador, String descricao) {
		String 	sql = "FROM Disciplina WHERE codigoDisciplina <> 0 ";

		if (!(descricao.isEmpty())) {
			sql += "AND descricao like '" + descricao + "%' ";  
		}
		
		if (!(identificador.isEmpty())) {
			sql += "AND identificador like '" + identificador + "%' ";  
		}
		
		sql += "ORDER BY descricao";		
 
		List<Disciplina> lista = hibernateDAO.getSession().createQuery(sql).list();

		return lista;
	}

	@Override
	public Disciplina getDisciplina(int codigoDisciplina) {
		
		Disciplina disciplina = hibernateDAO.get(codigoDisciplina);
		return disciplina;
	}

	@Override
	public List<Disciplina> getListTodos() {
		
		List<Disciplina> list = hibernateDAO.listAll();
		return list;
	}

	
	@SuppressWarnings("unchecked")
	@Override
	public boolean isExiste(Disciplina disciplina) {
		// SQL para verificar se a Disciplina existe
		String 	sql = 	"FROM Disciplina " +
				"WHERE identificador = '"+disciplina.getIdentificador()+"'"+
				" AND codigoDisciplina <> " + disciplina.getCodigoDisciplina();

		List<Disciplina> lista = hibernateDAO.getSession().createQuery(sql).list();
		if(lista.size()<1){
			return false;
		} else {
			return true;
		}
	}

}
